package com.emser.unc.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.jdo.JDOCanRetryException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

import org.datanucleus.store.appengine.query.JDOCursorHelper;

import com.emser.unc.serializable.CustomerDTO;
import com.emser.unc.serializable.CustomerRequestDTO;
import com.emser.unc.serializable.ResultDTO;
import com.emser.unc.serializable.SellerDTO;
import com.emser.unc.server.domain.Customer;
import com.emser.unc.server.domain.CustomerIndex;
import com.emser.unc.server.domain.Seller;
import com.emser.unc.server.domain.SellerCustomers;
import com.emser.unc.server.domain.UserAccount;
import com.google.appengine.api.datastore.Cursor;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class AppLibCustomer {
	private static final int NUM_RETRIES = 5;
	
	@SuppressWarnings("unchecked")
	public static Integer getCustomersCount(String userAName){
		PersistenceManager pm = PMF.get().getPersistenceManager();
	    Transaction tx = null;
	    Integer customerCount = 0;
	    List<Customer> customerList = null;
		List<Customer> resulta = null;
	    Key userKey = KeyFactory.createKey(UserAccount.class.getSimpleName(), userAName);
	    Query q = pm.newQuery(Customer.class);
	    q.setFilter("userA == :userName");
	    try {
	      for (int i = 0; i < NUM_RETRIES; i++) {
	        tx = pm.currentTransaction();
	        tx.begin();
	        customerList =(List<Customer>) q.execute(userKey); 
	        resulta = (List<Customer>)pm.detachCopyAll(customerList);
	        if(resulta != null && !resulta.isEmpty())
	        	customerCount = resulta.size();
	        try {
	          tx.commit();
	          break;
	        }
	        catch (JDOCanRetryException e1) {
	          if (i == (NUM_RETRIES - 1)) {
	            throw e1;
	          }
	        }
	      } 
	    }
	    catch (Exception e) {
	      e.printStackTrace();
	    }
	    finally {
	      if (tx.isActive()) {
	        tx.rollback();
	      }
	      pm.close();
	    }		
		return customerCount;	
	}
	
	@SuppressWarnings("unchecked")
	public static ResultDTO<CustomerDTO> getSearchCustomers(String pageCursor, int range,ArrayList<String> searchParam) {
		List<Customer> customersDB = null;
		ResultDTO<CustomerDTO> result = null;
		List<Customer> customersDBCopy = null;
		Key userKey = KeyFactory.createKey(UserAccount.class.getSimpleName(), searchParam.get(0));
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(Customer.class);
		if (searchParam.size()== 2){		
			q.setFilter("firstName >= :1 && firstName < :2 && userA == :3");
			q.setOrdering("firstName asc");
			q.setRange(0, range);
			if (pageCursor != null) {
	        	Cursor cursor = Cursor.fromWebSafeString(pageCursor);
	        	Map<String, Object> extensionMap = new HashMap<String, Object>();
	        	extensionMap.put(JDOCursorHelper.CURSOR_EXTENSION, cursor);
	        	q.setExtensions(extensionMap);
	        }
			customersDB = (List<Customer>) q.execute(searchParam.get(1)  , (searchParam.get(1) + "\ufffd"),userKey);			
		}
		if (searchParam.size() == 3){
			q.declareParameters("String first, String lastN, String lastN1,com.google.appengine.api.datastore.Key uName");
			q.setFilter("firstName == first && lastName >= lastN && lastName < lastN1 && userA == uName");
			q.setOrdering("firstName asc");
			q.setRange(0, range);
			if (pageCursor != null) {
	        	Cursor cursor = Cursor.fromWebSafeString(pageCursor);
	        	Map<String, Object> extensionMap = new HashMap<String, Object>();
	        	extensionMap.put(JDOCursorHelper.CURSOR_EXTENSION, cursor);
	        	q.setExtensions(extensionMap);
	        }
			Object[] parameters = new Object[]{ searchParam.get(1), searchParam.get(2), searchParam.get(2)+"\ufffd", userKey };
			customersDB = (List<Customer>) q.executeWithArray(parameters);
		}
		if (searchParam.size()== 4){
			q.declareParameters("String first, String lastN, Long iD,com.google.appengine.api.datastore.Key uName");
			q.setFilter("firstName == first && lastName == lastN && id == iD && userA == uName");
			q.setOrdering("firstName asc");
			q.setRange(0, range);
			if (pageCursor != null) {
	        	Cursor cursor = Cursor.fromWebSafeString(pageCursor);
	        	Map<String, Object> extensionMap = new HashMap<String,Object>();
	        	extensionMap.put(JDOCursorHelper.CURSOR_EXTENSION, cursor);
	        	q.setExtensions(extensionMap);
	        }
			Long iD =Long.parseLong(searchParam.get(3));
			Object[] parameters = new Object[] { searchParam.get(1), searchParam.get(2),iD , userKey };
			customersDB = (List<Customer>) q.executeWithArray(parameters);
		}
		if (customersDB != null) {
			customersDBCopy = (List<Customer>)pm.detachCopyAll(customersDB);
	        Cursor cursor = JDOCursorHelper.getCursor(customersDB);
	        pageCursor = cursor.toWebSafeString();
	        result = new ResultDTO<CustomerDTO>();
	        result.setCursorString(pageCursor);
			result.setList(toDTO(customersDBCopy));
        }
		q.closeAll();
		pm.close();
		return result;	
	}	
	
	public static Long addNewCustomer(CustomerRequestDTO customerRequest){
		Customer customer = createCustomerDB(customerRequest.getNewCustomer());
		Seller s = null;
		SellerCustomers sellerCustomers = null;
		CustomerIndex ci = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
	    Transaction tx = null;
	    Long result = null;
	    Query q = pm.newQuery(Seller.class);
	    q.setFilter("userName == :1");
	    q.setUnique(true);
	    try {
	      for (int i = 0; i < NUM_RETRIES; i++) {
	        tx = pm.currentTransaction();
	        tx.begin();
	        s = (Seller)q.execute(customerRequest.getSellerUserName());
	        KeyFactory.Builder sellerCKeyBuilder = new KeyFactory.Builder(s.getKey());
	    	sellerCKeyBuilder.addChild(SellerCustomers.class.getSimpleName(), s.getUserName());
	    	Key sellerCustomersKey = sellerCKeyBuilder.getKey();
	    	
			try{
				sellerCustomers = pm.getObjectById(SellerCustomers.class,sellerCustomersKey);
	        }catch(Exception e){
	        	sellerCustomers = new SellerCustomers(sellerCustomersKey,s.getUserName());
	        }
			s.getUserA().addCustomer(customer);
	        pm.makePersistent(customer);
	        customer.setId();
	        sellerCustomers.getIdCustomers().add(customer.getId());
	        KeyFactory.Builder keyBuilderTwo = new KeyFactory.Builder(UserAccount.class.getSimpleName(), customer.getKey().getParent().getName());
			keyBuilderTwo.addChild(Customer.class.getSimpleName(), customer.getId()).addChild(CustomerIndex.class.getSimpleName(), customer.getId());
			Key ckeyTwo = keyBuilderTwo.getKey();
			try{
				ci = pm.getObjectById(CustomerIndex.class, ckeyTwo);
	      	}catch(javax.jdo.JDOObjectNotFoundException e){
				ci = null;
			}
			if (ci == null) {
				ci = new CustomerIndex(customerRequest.getSellerUserName(), ckeyTwo);
				pm.makePersistent(ci);
				}
			else{
				ci.addSellerKey(customerRequest.getSellerUserName());
				pm.makePersistent(ci);
			}
			pm.makePersistent(sellerCustomers);
	        result = customer.getId();
	        try {
	          tx.commit();
	          break;
	        }
	        catch (JDOCanRetryException e1) {
	          if (i == (NUM_RETRIES - 1)) {
	            throw e1;
	          }
	        }
	      } 
	    }
	    catch (Exception e) {
	      e.printStackTrace();
	      result = null;
	    }
	    finally {
	      if (tx.isActive()) {
	        tx.rollback();
	      }
	      q.closeAll();
	      pm.close();
	    }
		return result;
	}
	
	public static boolean addCustomerDataStore(String userAName, CustomerDTO customerDTO) {
		Customer customer = createCustomerDB(customerDTO);
		PersistenceManager pm = PMF.get().getPersistenceManager();
	    Transaction tx = null;
	    UserAccount user = null;
	    Key k = KeyFactory.createKey(UserAccount.class.getSimpleName(), userAName);
	    try {
	      for (int i = 0; i < NUM_RETRIES; i++) {
	        tx = pm.currentTransaction();
	        tx.begin();
	        user = pm.getObjectById(UserAccount.class, k);
	        user.addCustomer(customer);
	        customer.setId();
	        try {
	          tx.commit();
	          break;
	        }
	        catch (JDOCanRetryException e1) {
	          if (i == (NUM_RETRIES - 1)) {
	            throw e1;
	          }
	        }
	      } 
	    }
	    catch (Exception e) {
	      e.printStackTrace();
	    }
	    finally {
	      if (tx.isActive()) {
	        tx.rollback();
	      }
	      pm.close();
	    }
		return true;
	}
	
	@SuppressWarnings("unchecked")
	public static ResultDTO<CustomerDTO> getCustomersDataStore(String pageCursor, int range,String userAName){
		PersistenceManager pm = PMF.get().getPersistenceManager();
	    Transaction tx = null;
	    List<Customer> customerList = null;
		List<Customer> customerListCopy = null;
		ResultDTO<CustomerDTO> result = new ResultDTO<CustomerDTO>();
		Query q = pm.newQuery(Customer.class);
		q.setFilter("userA == :userName");
		q.setOrdering("firstName asc");
	    Key userName = KeyFactory.createKey(UserAccount.class.getSimpleName(), userAName);
	    if (pageCursor != null) {
        	Cursor cursor = Cursor.fromWebSafeString(pageCursor);
        	Map<String, Object> extensionMap = new HashMap<String,
        	Object>();
        	extensionMap.put(JDOCursorHelper.CURSOR_EXTENSION, cursor);
        	q.setExtensions(extensionMap);
        }
	    try {
	      for (int i = 0; i < NUM_RETRIES; i++) {
	        tx = pm.currentTransaction();
	        tx.begin();
	        q.setRange(0, range);
	        customerList = (List<Customer>) q.execute(userName);
	        if (customerList.iterator().hasNext()) {
		        customerListCopy = (List<Customer>)pm.detachCopyAll(customerList);
		        Cursor cursor = JDOCursorHelper.getCursor(customerList);
		        pageCursor = cursor.toWebSafeString();
	        }
	        else {
	        	pageCursor = null;
	        }
	        
	        try {
	          tx.commit();
	          break;
	        }
	        catch (JDOCanRetryException e1) {
	          if (i == (NUM_RETRIES - 1)) {
	            throw e1;
	          }
	        }
	      } 
	    }
	    catch (Exception e) {
	      e.printStackTrace();
	      return null;
	    }
	    finally {
	      if (tx.isActive()) {
	        tx.rollback();
	      }
	      q.closeAll();
	      pm.close();
	    }
	    if(customerListCopy != null){
	    	result.setList(toDTO(customerListCopy));
	    	result.setCursorString(pageCursor);
        	return result;
	    }
	    else return null;
		
	}
	
	public static ArrayList<CustomerDTO> toDTO(List<Customer> customers){
		ArrayList<CustomerDTO> customersDTO = new ArrayList<CustomerDTO>();
        for(int i = 0;i<customers.size();i++)
        	customersDTO.add(Customer.toDTO(customers.get(i)));
        return customersDTO;
	}
	
	public static boolean updateCustomerDataStore(String userAName,CustomerDTO customerDTO) {
		boolean result = false;
		Customer customer = null;
		CustomerIndex customerIndex = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
	    Transaction tx = null;
	    KeyFactory.Builder keyBuilder = new KeyFactory.Builder(UserAccount.class.getSimpleName(), userAName);
		keyBuilder.addChild(Customer.class.getSimpleName(), customerDTO.getCode()).addChild(CustomerIndex.class.getSimpleName(), customerDTO.getCode());
		Key ckey = keyBuilder.getKey();
	    Query q = pm.newQuery(Customer.class, "id == :idCustomer");
		q.setUnique(true);
	    try {
	      for (int i = 0; i < NUM_RETRIES; i++) {
	        tx = pm.currentTransaction();
	        tx.begin();
	        customer = (Customer) q.execute(customerDTO.getCode());
	        customer.setFirstName(customerDTO.getFirstName());
			customer.setLastName(customerDTO.getLastName());
			customer.setAddress(customerDTO.getAddress());
			customer.setTelephone(customerDTO.getTelephone());
			try{
				customerIndex = pm.getObjectById(CustomerIndex.class, ckey);
	      	}catch(javax.jdo.JDOObjectNotFoundException e){
				customerIndex = null;
			}
	      	if (customerIndex != null) {
				Iterator<String> it = customerIndex.getUserNameSellers().iterator();
				while(it.hasNext()){
					String sellerN = it.next();
					KeyFactory.Builder keyBuilderTwo = new KeyFactory.Builder(UserAccount.class.getSimpleName(), userAName);
					keyBuilderTwo.addChild(Seller.class.getSimpleName(), sellerN);
					Key ckeyTwo = keyBuilderTwo.getKey();
					Seller s = pm.getObjectById(Seller.class, ckeyTwo);
					s.setVersionCustomer(s.getVersionCustomer()+new Long(1));
					pm.makePersistent(s);
				}
			}
	        try {
	          tx.commit();
	          result = true;
	          break;
	        }
	        catch (JDOCanRetryException e1) {
	          if (i == (NUM_RETRIES - 1)) {
	            throw e1;
	          }
	        }
	      } 
	    }
	    catch (Exception e) {
	      e.printStackTrace();
	    }
	    finally {
	      if (tx.isActive()) {
	        tx.rollback();
	      }
	      q.closeAll();
	      pm.close();
	    }
		return result;
	}
	
	public static ArrayList<CustomerDTO> getSellerCustomers(SellerDTO sellerDTO){
		SellerCustomers sellerCustomers = getSellerCustomers(sellerDTO.getUserName());
		if((sellerCustomers != null)&&(!sellerCustomers.getIdCustomers().isEmpty())){
			List<Customer> customers = AppLibCustomer.getCustomers(sellerCustomers.getIdCustomers());
			if (customers == null)
				return null;
			else
				return toDTO(customers);
		}
		else return null;	
	}
	
	public static CustomerDTO getCustomer(Long id) {
			Customer customer = null, detached = null;
			if(id == null)
				return null;
			PersistenceManager pm = PMF.get().getPersistenceManager();
		    Transaction tx = null;
		    Query q = pm.newQuery(Customer.class, "id == :idParam");
			q.setUnique(true);
		    try {
		      for (int i = 0; i < NUM_RETRIES; i++) {
		        tx = pm.currentTransaction();
		        tx.begin();
		        customer = (Customer) q.execute(id);
				if (customer != null) {
					detached = pm.detachCopy(customer);
				}
		        try {
		          tx.commit();
		          break;
		        }
		        catch (JDOCanRetryException e1) {
		          if (i == (NUM_RETRIES - 1)) {
		            throw e1;
		          }
		        }
		      } 
		    }
		    catch (Exception e) {
		      e.printStackTrace();
		    }
		    finally {
		      if (tx.isActive()) {
		        tx.rollback();
		      }
		      q.closeAll();
		      pm.close();
		    }
		    return Customer.toDTO(detached);
	}
	
	public static boolean deleteCSellerReferences(String userAName,String sellerUName,List<Long> customersIDs){
		CustomerIndex customerIndex = null;
		boolean result = false;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Iterator<Long> itcustomer = customersIDs.iterator();	
		Transaction tx = null;
		try {
		      for (int i = 0; i < NUM_RETRIES; i++) {
		        tx = pm.currentTransaction();
		        tx.begin();
		        while(itcustomer.hasNext()){
		        	Long idCustomer = itcustomer.next();
		        	KeyFactory.Builder keyBuilder = new KeyFactory.Builder(UserAccount.class.getSimpleName(), userAName);
		        	keyBuilder.addChild(Customer.class.getSimpleName(), idCustomer).addChild(CustomerIndex.class.getSimpleName(), idCustomer);
		        	Key customerKey = keyBuilder.getKey();
		        	try{						
		        		customerIndex = pm.getObjectById(CustomerIndex.class, customerKey);
		        	}catch(javax.jdo.JDOObjectNotFoundException e){
		        		customerIndex = null;
		        	}
		        	if(customerIndex != null){
		        		customerIndex.getUserNameSellers().remove(sellerUName);
		        		if(customerIndex.getUserNameSellers().isEmpty())
		        			pm.deletePersistent(customerIndex);
		        	}
		        }
		        try {
			         tx.commit();
			         result = true;
			         break;
			    }
			    catch (JDOCanRetryException e1) {
			         if (i == (NUM_RETRIES - 1)) {
			           throw e1;
			         }
			    }
		      }
		}
		catch (Exception e) {
			result = false;
			e.printStackTrace();
		}
		finally {
			if (tx.isActive()) {
			   tx.rollback();
			}
			pm.close();
		}
		return result;      
	}
	
	public static SellerCustomers getSellerCustomers(String sellerKey){
		SellerCustomers result = null, resultCopy = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(SellerCustomers.class,"sellerKey == :sellerKey");
		q.setUnique(true);
		try{
			result = (SellerCustomers) q.execute(sellerKey);
			resultCopy = pm.detachCopy(result);
		}
		catch(Exception e){
			e.printStackTrace();
		}
		finally{
			q.closeAll();
			pm.close();
		}
		return resultCopy;
		
	}
	
	public static boolean addCustomersSeller(List<Long> customersIds,
			String sellerUName,String userAName) {
		SellerCustomers sellerCustomers = null;
		CustomerIndex customerIndex = null;
		boolean flag = true;
		Transaction tx = null;
		Iterator<Long> iterator = customersIds.iterator();
		Seller seller = AppLibSeller.getSeller(sellerUName);
		sellerCustomers = getSellerCustomers(sellerUName);
		if(sellerCustomers == null){
			KeyFactory.Builder sellerCKeyBuilder = new KeyFactory.Builder(UserAccount.class.getSimpleName(), userAName);
	    	sellerCKeyBuilder.addChild(Seller.class.getSimpleName(), sellerUName).addChild(SellerCustomers.class.getSimpleName(), sellerUName);
	    	Key sellerCustomersKey = sellerCKeyBuilder.getKey();
			sellerCustomers = new SellerCustomers(sellerCustomersKey,sellerUName);
		}
		if((!sellerCustomers.getIdCustomers().isEmpty())){
			flag = deleteCSellerReferences(userAName,sellerUName,sellerCustomers.getIdCustomers());
			sellerCustomers.getIdCustomers().clear();
		}
		if(flag){
			PersistenceManager pm = PMF.get().getPersistenceManager();
			seller.setVersionCustomer(seller.getVersionCustomer() + new Long(1));
			sellerCustomers.setIdCustomers(new ArrayList<Long>());
			try {
			      for (int i = 0; i < NUM_RETRIES; i++) {
			        tx = pm.currentTransaction();
			        tx.begin();
			        while(iterator.hasNext()){
			        	Long customerId = iterator.next();
			        	sellerCustomers.getIdCustomers().add(customerId);
			        	KeyFactory.Builder customerIKeyBuilder = new KeyFactory.Builder(UserAccount.class.getSimpleName(), userAName);
			        	customerIKeyBuilder.addChild(Customer.class.getSimpleName(), customerId).addChild(CustomerIndex.class.getSimpleName(), customerId);
			        	Key customerIndexKey = customerIKeyBuilder.getKey();
			        	try{
			        		customerIndex = pm.getObjectById(CustomerIndex.class, customerIndexKey);
			        	}catch(javax.jdo.JDOObjectNotFoundException e){
			        		customerIndex = null;
			        	}
			        	if (customerIndex == null) {
			        		customerIndex = new CustomerIndex(sellerUName, customerIndexKey);
			        		pm.makePersistent(customerIndex);
			        	}
			        	else{
			        		customerIndex.addSellerKey(sellerUName);
			        		pm.makePersistent(customerIndex);
			        	}
			        }
			        pm.makePersistent(seller);
			        pm.makePersistent(sellerCustomers);
			        try {
				         tx.commit();
				         break;
				    }
				    catch (JDOCanRetryException e1) {
				         if (i == (NUM_RETRIES - 1)) {
				           throw e1;
				         }
				    }
			      }
			}
			catch (Exception e) {
				e.printStackTrace();
				return false;
			}
			finally {
				if (tx.isActive()) {
				   tx.rollback();
				}
				pm.close();
			}
		}
		return flag;
	}
	
	public static boolean deleteCustomer(String userAName,Customer customer){
			CustomerIndex customerIndex;
			boolean result = false;
			PersistenceManager pm = PMF.get().getPersistenceManager();
			KeyFactory.Builder keyBuilderCIndex = new KeyFactory.Builder(UserAccount.class.getSimpleName(), userAName);
        	keyBuilderCIndex.addChild(Customer.class.getSimpleName(), customer.getId()).addChild(CustomerIndex.class.getSimpleName(), customer.getId());
        	Key customerIndexKey = keyBuilderCIndex.getKey();
        	KeyFactory.Builder keyBuilderCustomer = new KeyFactory.Builder(UserAccount.class.getSimpleName(), userAName);
        	keyBuilderCustomer.addChild(Customer.class.getSimpleName(), customer.getId());
        	Key customerKey = keyBuilderCustomer.getKey();
    		Transaction tx = null;
    		try{
    			for (int i = 0; i < NUM_RETRIES; i++) {
			        tx = pm.currentTransaction();
			        tx.begin();
			        try{
			        	customerIndex = pm.getObjectById(CustomerIndex.class, customerIndexKey);
			        	Set<String> sellersUNames = customerIndex.getUserNameSellers();
			        	Iterator<String> itsellerUName = sellersUNames.iterator();
			        	while(itsellerUName.hasNext()){
			        		String sellerUName = itsellerUName.next(); 
			        		KeyFactory.Builder sellerCKeyBuilder = new KeyFactory.Builder(UserAccount.class.getSimpleName(), userAName);
			            	sellerCKeyBuilder.addChild(Seller.class.getSimpleName(), sellerUName).addChild(SellerCustomers.class.getSimpleName(), sellerUName);
			            	Key sellerCKey = sellerCKeyBuilder.getKey();
			            	KeyFactory.Builder sellerKeyBuilder = new KeyFactory.Builder(UserAccount.class.getSimpleName(), userAName);
			            	sellerKeyBuilder.addChild(Seller.class.getSimpleName(), sellerUName);
			            	Key sellerKey = sellerKeyBuilder.getKey();			            	
			        		SellerCustomers sellerCustomers = pm.getObjectById(SellerCustomers.class,sellerCKey);
			        		sellerCustomers.getIdCustomers().remove(customer.getId());
			        		Seller seller = pm.getObjectById(Seller.class, sellerKey);
			        		seller.setVersionCustomer(seller.getVersionCustomer()+ new Long(1));
			        		if(sellerCustomers.getIdCustomers().isEmpty())
			        			sellerCustomers.setIdCustomers(new ArrayList<Long>());	
			        		pm.makePersistent(sellerCustomers);
			        	}
			        	pm.deletePersistent(customerIndex);
			        }catch(javax.jdo.JDOObjectNotFoundException e){}
			        try{
			        	Customer c = pm.getObjectById(Customer.class,customerKey);			        	
			        	pm.deletePersistent(c);
			        	result = true;
			        }
			        catch(Exception e){}
		        	
			        try {
				         tx.commit();
				         break;
				    }
				    catch (JDOCanRetryException e1) {
				         if (i == (NUM_RETRIES - 1)) {
				           throw e1;
				         }
				    }
			      }
			}
			catch (Exception e) {
				result = false;
				e.printStackTrace();
			}
			finally {
				if (tx.isActive()) {
				   tx.rollback();
				}
				pm.close();
			}
			return result;
	}
	
	public static boolean deleteCustomersDataStore(String userAName, ArrayList<Long> customerIds) {	
		boolean result = false;
	    List<Customer> customersDB = null;
        customersDB = getCustomers(customerIds);
        if(customersDB != null){
        	result = true;
        	Iterator<Customer> iterator= customersDB.iterator();
        	while((iterator.hasNext())&&(result)){
        		Customer customer = iterator.next();
        		result = deleteCustomer(userAName,customer);
        	}
        }
        return result;
	}
	
	@SuppressWarnings("unchecked")
	public static List<Customer> getCustomers(List<Long> customersIDs){
		List<Customer> customers = null;
		List<Customer> result = null;
		if(customersIDs.isEmpty()||customersIDs ==null)
			return result;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery("select from " +Customer.class.getName()+" where id == :keys"); //order by firstName asc
		try{
			customers = (List<Customer>)q.execute(customersIDs);
			if(customers != null)
				result = (List<Customer>)pm.detachCopyAll(customers);
		}catch(Exception e){
			e.printStackTrace();
		}
		finally{
			q.closeAll();
			pm.close();			
		}
		return result; 
		
	}
	
	private static Customer createCustomerDB(CustomerDTO customerDTO){
		Customer customer = new Customer();
		customer.setFirstName(customerDTO.getFirstName());
		customer.setCity(customerDTO.getCity());
		customer.setZipCode(customerDTO.getZipCode());
		customer.setLastName(customerDTO.getLastName());
		customer.setAddress(customerDTO.getAddress());
		customer.setTelephone(customerDTO.getTelephone());
		return customer;	
	}

	@SuppressWarnings("unchecked")
	public static Integer getSearchedCustomersCount(
			ArrayList<String> searchParam) {
		List<Customer> customersList = new ArrayList<Customer>();
		Integer result = 0;
		Key userName = KeyFactory.createKey(UserAccount.class.getSimpleName(), searchParam.get(0));
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(Customer.class);
		if (searchParam.size()<= 2){	
			q.setFilter("firstName >= :1 && firstName < :2 && userA == :3");			
			customersList = (List<Customer>) q.execute(searchParam.get(1)  , (searchParam.get(1) + "\ufffd"),userName);
		}
		if (searchParam.size() == 3){
			q.declareParameters("String first, String lastN, String lastN1,com.google.appengine.api.datastore.Key uName");
			q.setFilter("firstName == first && lastName >= lastN && lastName < lastN1 && userA == uName");
			Object[] parameters = new Object[]{ searchParam.get(1), searchParam.get(2), searchParam.get(2)+"\ufffd", userName };
			customersList = (List<Customer>) q.executeWithArray(parameters);
		}
		if (searchParam.size()>= 4){
			q.declareParameters("String first, String lastN, Long iD,com.google.appengine.api.datastore.Key uName");
			q.setFilter("firstName == first && lastName == lastN && id == iD && userA == uName");
			q.setOrdering("firstName asc");
			Long iD =Long.parseLong(searchParam.get(3));
			Object[] parameters = new Object[] { searchParam.get(1), searchParam.get(2),iD , userName };
			customersList = (List<Customer>) q.executeWithArray(parameters);			
		}
		if(customersList != null){
			result = customersList.size();
		}
		q.closeAll();
		pm.close();
		return result;
	}
}
